package com.admin.service.sample.impl;

import com.admin.common.context.SampleContext;
import com.admin.common.enums.DeclareScoreStatusEnum;
import com.admin.common.enums.sample.SampleTypeEnum;
import com.admin.common.exception.BizException;
import com.admin.common.util.DateUtils;
import com.admin.common.util.RandomUtil;
import com.admin.domain.Declare;
import com.admin.mapper.DeclareMapper;
import com.admin.service.sample.SampleService;
import com.admin.vo.sample.SampleResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>省抽样</p>
 *
 * @author : weiyang
 * @date : 2022-06-06 10:29
 **/
@Service
@Slf4j
public class ProvinceSampleServiceImpl implements SampleService {

    @Autowired
    private DeclareMapper declareMapper;

    @Override
    public SampleTypeEnum getType() {
        return SampleTypeEnum.PROVINCE_SAMPLE;
    }

    @Override
    public SampleResponse sample(SampleContext sampleContext) {
        Map<String,Object> params = new HashMap();
        params.put("startTime", DateUtils.dateFormatStr(sampleContext.getStartTime()));
        params.put("endTime", DateUtils.dateFormatStr(sampleContext.getEndTime()));
        params.put("declareType", sampleContext.getDeclareType());
        params.put("scoreStatus", DeclareScoreStatusEnum.PROVINCE_WAIT.getKey());
        params.put("isSubmitProvince", 1);
        params.put("provinceIds", sampleContext.getProvinceIdList());

        //所有待省级评分的样本总数
        List<Integer> idList = declareMapper.selectIdsByMap(params);
        if (CollectionUtils.isEmpty(idList)) {
            throw new BizException(-1, "暂无可抽样的数据");
        }
        
        Integer totalNum = idList.size();
        //需要抽样的数量
        int needSampleNum = (int) Math.ceil(totalNum * sampleContext.getSampleRate() / 100d);

        //生成抽样随机数（这里为数组下标）
        List<Integer> numberList = RandomUtil.getRandomList(idList.size(), needSampleNum);

        //样本结果
        List<Integer> sampleIdList = numberList.stream().map(index -> {
            return idList.get(index);
        }).collect(Collectors.toList());

        List<Declare> declareList = declareMapper.selectSimpleByIds(sampleIdList);
        Map<Integer, List<Declare>> cityGroupMap = declareList.stream().collect(Collectors.groupingBy(Declare::getCityId));
        Map<Integer, List<Declare>> areaGroupMap = declareList.stream().collect(Collectors.groupingBy(Declare::getAreaId));

        //结果封装
        SampleResponse sampleResponse = new SampleResponse();
        sampleResponse.setIdList(sampleIdList);
        sampleResponse.setSampleQuantity(needSampleNum);
        sampleResponse.setCityQuantity(cityGroupMap.size());
        sampleResponse.setAreaQuantity(areaGroupMap.size());
        return sampleResponse;
    }

}
